package com.lyn.qrcode;

import android.graphics.Rect;

import com.yanzhenjie.zbar.Image;
import com.yanzhenjie.zbar.ImageScanner;
import com.yanzhenjie.zbar.Symbol;
import com.yanzhenjie.zbar.SymbolSet;

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * Zbar 二维码管理器
 *
 * @author Lyn 2022/12/25
 * @version 1.0.0
 */
public class ZbarManager {

    private final ImageScanner imageScanner;
    private final Image image;
    private final int width;
    private final int height;


    public ZbarManager(int width, int height) {
        this.width = width;
        this.height = height;
        imageScanner = new ImageScanner();
        image = new Image(width, height, "Y800");
    }


    private final List<ZbarData> zbarDataList = new CopyOnWriteArrayList<>();

    public List<ZbarData> decode(byte[] nv21Data) {
        return decode(nv21Data, this.width, this.height);
    }

    public List<ZbarData> decode(byte[] nv21Data, int nv21Width, int nv21Height) {
        image.setSize(nv21Width, nv21Height);
        image.setData(nv21Data);
        zbarDataList.clear();
        int result = imageScanner.scanImage(image);
        if (result == 0) {
            zbarDataList.clear();
            return zbarDataList;
        }
        SymbolSet symSet = imageScanner.getResults();
        for (Symbol sym : symSet) {
            if (sym == null) {
                continue;
            }
            int[] coordinate = sym.getBounds();
            Rect rect = new Rect();
            rect.left = coordinate[0];
            rect.top = coordinate[1];
            rect.right = (coordinate[0] + coordinate[2]);
            rect.bottom = (coordinate[1] + coordinate[3]);
            ZbarData qrCodeZbarData = new ZbarData(sym.getData(), rect, System.currentTimeMillis());
            zbarDataList.add(qrCodeZbarData);
        }
        return zbarDataList;
    }

    public void destroy() {
        imageScanner.destroy();
        image.destroy();
    }
}
